

package com.iavstream.blife.ui;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Point;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;

import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


import com.iavstream.blife.BLifeApplication;
import com.iavstream.blife.R;

import com.iavstream.libavstream.CameraInterface.OnJniStateChangeListener;
import com.iavstream.libavstream.CameraService;
import com.iavstream.libavstream.CameraTextureView;
import com.iavstream.libavstream.MediaParameter;

import com.iavstream.utility.DisplayStatus;
import com.iavstream.utility.DisplayUtil;
import com.iavstream.utility.StreamAddressStuff;


public class PreviewFragment extends Fragment implements TextureView.SurfaceTextureListener {

	public final static String TAG = "BLifeApplication_PreviewFragment";

	private TextView mTextView;
	ImageButton shutterBtn;
	float previewRate = -1f;
	CameraTextureView textureView = null;
	SurfaceTexture mSurface;
	MediaParameter mediaparameter= null;
	private CameraService cameraService;
	private boolean startorstop=false;
	private DisplayStatus statsView = null;
	View rootView;
	private BLifeApplication mApplication;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mApplication = (BLifeApplication)getActivity().getApplication();
	}

	
	private void initViewParams(){

		LayoutParams params = textureView.getLayoutParams();
		Point p = DisplayUtil.getScreenMetrics(getActivity());
		params.width = p.x;
		params.height = p.y;
		previewRate = DisplayUtil.getScreenRate(getActivity()); 
		textureView.setLayoutParams(params);
		
		LayoutParams p2 = shutterBtn.getLayoutParams();
		p2.width = DisplayUtil.dip2px(getActivity(), 50);
		p2.height = DisplayUtil.dip2px(getActivity(), 50);;		
		shutterBtn.setLayoutParams(p2);
		
		LayoutParams p3 = mTextView.getLayoutParams();
		p3.width = DisplayUtil.dip2px(getActivity(), 100);
		p3.height = DisplayUtil.dip2px(getActivity(), 50);;		
		mTextView.setLayoutParams(p3);
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
    public void onResume() {
    	super.onResume();
    	if(mediaparameter!=null)
        {
    		boolean i =equals(mediaparameter,getMediaParameter());
    		if(i==false)
    		{
    			mediaparameter=getMediaParameter();
    		}
        }
    	RefreshState();
    }
	
	public void RefreshState()
	{
        if(statsView!=null&&mediaparameter!=null){
			
			statsView.setWillNotDraw(true);
			statsView.SetMediaParameter(mediaparameter);
			statsView.setWillNotDraw(false);
		}
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		rootView = inflater.inflate(R.layout.preview,container,false);
		mTextView = (TextView)rootView.findViewById(R.id.tooltip);
		
		textureView = (CameraTextureView)rootView.findViewById(R.id.camera_textureview);
		shutterBtn = (ImageButton)rootView.findViewById(R.id.btn_shutter);
		
		statsView = (DisplayStatus)rootView.findViewById(R.id.display_status);
		statsView.setBackgroundColor(0);
		
		textureView.setAlpha(1.0f);
		initViewParams();		
		
		shutterBtn.setOnClickListener(new BtnListeners());
		textureView.setSurfaceTextureListener(this);
		return rootView;
	}
	
	private class BtnListeners implements OnClickListener{

		@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.btn_shutter:
				startorstop=!startorstop;
				if(startorstop)
				{
					mTextView.setText("start");
					connection();
				}
				else
				{
					mTextView.setText("stop");
					disconnection();
				}
				break;
			default:break;
			}
		}

	}
	
	private void connection() {
		Intent intent = new Intent("com.iavstream.libavstream.CameraService");
		getActivity().bindService(intent, sc, Context.BIND_AUTO_CREATE);
	}
	
	private void disconnection() {
		if(sc != null){
			getActivity().unbindService(sc);
		}		
	}
	
	private ServiceConnection sc = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//connect Service
			cameraService = ((CameraService.MyBinder) (service)).getService();
			if(cameraService != null)
			{				
			  mediaparameter=getMediaParameter();			  
			  cameraService.prepare(mediaparameter);			  
			  cameraService.startpreview(mSurface, previewRate);			  
			  cameraService.getCameraInterface().setOnJniStateChangeListener(new OnJniStateChangeListener(){
				  public void OnJniStateChange(int state) {

					 String str = "no error";
					 switch (state)
					 {
					    case -1: str="ERROR_ALLOC_CONTEXT";break;
					    case -2: str="ERROR_OPEN_FILE";	break;
					    case -3: str="无法连接到服务器,请检查后重试";break;	
					    case -4: str="ERROR_THREAD_VIDEOENCODING";break;
					    case -5: str="ERROR_THREAD_AUDIOENCODING";break;
					    case -6: str="网络质量差,直播中断";break;
					    case -7: str="网络质量差,直播中断";break;
					    case -8: str="网络质量差,直播中断";break;
					 
					 }
					 DisplayToast("error :"+str);
					 cameraService.stop();
					 cameraService = null;
				}
				  
			  });
			  RefreshState();
			}
		}
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			//disconnect Service
			cameraService.stop();
			cameraService = null;
		}
	};

	@Override
	public void onSurfaceTextureAvailable(SurfaceTexture surface, int arg1,
			int arg2) {
		mSurface = surface;

	}
	@Override
	public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
		return false;
	}

	@Override
	public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1,
			int arg2) {
		
	}

	@Override
	public void onSurfaceTextureUpdated(SurfaceTexture arg0) {
		
	}
	
	private void DisplayToast(String str)
	{
		Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();	
	}

	
	MediaParameter getMediaParameter()
	{
	    String []temp;	    
	    MediaParameter mp = new MediaParameter();
	    StreamAddressStuff ss=new StreamAddressStuff();
	    
		//1 format type set
		if(mApplication.streamaudioEnabled&&mApplication.streamvideoEnabled)
		{
			mp.formattype=1;
	    }
		else if(mApplication.streamaudioEnabled)
		{
			mp.formattype=3;
	    }
		else if(mApplication.streamvideoEnabled)
		{
			mp.formattype=2;
		}
		else
		{

		}
		//2 video audio parameter
		if(mp.formattype==1)
		{   //audio parameter
			mp.audio_bitrate=mApplication.audioBitrate*1000;
			
			//video parameter
			mp.video_camside=mApplication.videoCamSide;	
			
			mp.video_width=mApplication.videoQuality.resX;
			
			mp.video_height=mApplication.videoQuality.resY;
			
			mp.video_fps=mApplication.videoQuality.framerate;
			
			mp.video_bitrate=mApplication.videoQuality.bitrate;			

		}
		else if(mp.formattype==2)
		{
			//video parameter
			mp.video_camside=mApplication.videoCamSide;	
			
			mp.video_width=mApplication.videoQuality.resX;
			
			mp.video_height=mApplication.videoQuality.resY;
			
			mp.video_fps=mApplication.videoQuality.framerate;
			
			mp.video_bitrate=mApplication.videoQuality.bitrate;	
			
			
		}
		else if(mp.formattype==3)
		{
			mp.audio_bitrate=mApplication.audioBitrate*1000;			
		}
		else
		{

		}
		//3 stream type set
		if(mApplication.mpegtsEnabled)
		{
			mp.streamtype=1;
			temp=mApplication.mpegtsAddress.split(":");
			mp.tsaddress=temp[0];
			mp.portname=temp[1];
		}
		else if(mApplication.rtspEnabled)
		{
			mp.streamtype=2;
			mp.ipaddress=mApplication.rtspAddress;//ss.GetInetAddress(mApplication.rtspAddress);
			mp.sdpfilename=mApplication.sdpFilename;
		}		
		else
		{
			mp=new MediaParameter();
		}
		return mp;
	}
	
	boolean equals(MediaParameter mp1,MediaParameter mp2) {
    	
			if (mp1==null||mp2==null) return false;
			
			//check formattype
			if(mp1.formattype!=mp2.formattype)
			{
				return false;			
			}
			else if(mp1.formattype==1)//audio and video
			{
				if(mp1.audio_bitrate!=mp2.audio_bitrate)return false;
				
				if(mp1.video_bitrate!=mp2.video_bitrate
						||mp1.video_camside!=mp2.video_camside
						||mp1.video_fps!=mp2.video_fps
						||mp1.video_height!=mp2.video_height
						||mp1.video_width!=mp2.video_width)return false;
			}
			else if(mp1.formattype==2)//video
			{
				if(mp1.video_bitrate!=mp2.video_bitrate
						||mp1.video_camside!=mp2.video_camside
						||mp1.video_fps!=mp2.video_fps
						||mp1.video_height!=mp2.video_height
						||mp1.video_width!=mp2.video_width)return false;
				
			}
			else if(mp1.formattype==3)//audio
			{
				if(mp1.audio_bitrate!=mp2.audio_bitrate)return false;
				
			}		
			//check stream type
			if(mp1.streamtype!=mp2.streamtype)
			{
				return false;
			}
			else if(mp1.streamtype==1)//mpeg-ts
			{
				if(mp1.tsaddress.equals(mp2.tsaddress)==false||mp1.portname.equals(mp2.portname)==false)return false;			
			}
			else if(mp1.streamtype==2)//rtsp
			{
				
				if(mp1.ipaddress.equals(mp2.ipaddress)==false||mp1.sdpfilename.equals(mp2.sdpfilename)==false)return false;
			}
			
			return true;			
		}
	
	/*private void showCustomMessageOK(String pTitle, final String pMsg) {
		
		final Dialog lDialog = new Dialog(getActivity(),
				android.R.style.Theme_Translucent_NoTitleBar);
		
		lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		lDialog.setContentView(R.layout.r_okdialogview);
		((TextView) lDialog.findViewById(R.id.dialog_title)).setText(pTitle);
		((TextView) lDialog.findViewById(R.id.dialog_message)).setText(pMsg);
		((Button) lDialog.findViewById(R.id.ok)).setText("Ok");
		((Button) lDialog.findViewById(R.id.ok))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// write your code to do things after users clicks OK
						lDialog.dismiss();
					}
				});
 		lDialog.show();

	}*/
	    	
	
	
}
